<script setup lang="ts">
import { ref, reactive, nextTick, watch } from 'vue'
import { Plus } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from 'element-plus'
import CateTable from '@/components/CateTable.vue'
import { useCateStore } from '@/stores/cate.js'
import { cateAddService, cateListService } from '@/api/cate.js'

// 类型定义
type CategoryType = 1 | 2 | 3
type TabName = 'first' | 'second' | 'third'

interface CategoryForm {
  type: CategoryType
  fId: string | number
  sId: string | number
  category: string
}

// 状态管理
const activeName = ref<TabName>('first')
const showDialog = ref(false)
const formRef = ref()
const cateStore = useCateStore()
const cateLevel2 = ref<Array<{ id: number, category: string }>>([])
const submitting = ref(false) // 添加提交状态

// 表单数据
const form = reactive<CategoryForm>({
  type: 1,
  fId: '',
  sId: '',
  category: ''
})

// 表单验证规则
const rules = reactive({
  type: [{ required: true, message: '请选择类别', trigger: 'change' }],
  fId: [{
    required: true,
    message: '请选择一级分类',
    trigger: 'change',
    validator: (rule: any, value: any, callback: any) => {
      if (form.type !== 1 && !value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
  }],
  sId: [{
    required: true,
    message: '请选择二级分类',
    trigger: 'change',
    validator: (rule: any, value: any, callback: any) => {
      if (form.type === 3 && !value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
  }],
  category: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
})

// 一级分类变化处理
const handleFirstLevelChange = (id: number) => {
  const parentCategory = cateStore.cateLevel.find(item => item.id === id)
  cateLevel2.value = parentCategory?.children || []
  form.sId = ''
}

// 打开添加分类对话框
const openAddDialog = () => {
  showDialog.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    cateLevel2.value = []
    form.type = 1
    form.fId = ''
    form.sId = ''
    form.category = ''
  })
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
}

// 提交表单
const submitForm = async () => {
  try {
    submitting.value = true
    await formRef.value.validate()

    // 根据分类类型准备提交数据
    const submitData = {
      category: form.category
    }

    if (form.type === 2) {
      submitData.fId = form.fId
    } else if (form.type === 3) {
      submitData.sId = form.sId
    }

    await cateAddService({
      type: form.type,
      ...submitData
    })

    ElMessage.success('分类添加成功')
    closeDialog()
    await refreshCateList()
    refreshKey.value++
  } catch (error) {
    if (error !== 'validate') {
      console.error('添加分类失败:', error)
      ElMessage.error(error.response?.data?.message || '分类添加失败，请稍后重试')
    }
  } finally {
    submitting.value = false
  }
}

// 刷新分类列表
const refreshCateList = async () => {
  try {
    const { data } = await cateListService()
    cateStore.setCateLevel(data)
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败，请刷新页面重试')
  }
}
// 添加一个刷新计数器
const refreshKey = ref(0)

// 监听 activeName 变化
watch(activeName, () => {
  // 使用 nextTick 确保在 DOM 更新后执行
  nextTick(() => {
    refreshKey.value++
  })
})
</script>
<template>
  <el-card class="category-management">
    <template #header>
      <div class="card-header">
        <span class="header-title">分类管理</span>
        <el-button type="primary" size="small" :icon="Plus" @click="openAddDialog">
          添加分类
        </el-button>
      </div>
    </template>

    <el-tabs v-model="activeName" class="category-tabs">
      <el-tab-pane label="一级分类" name="first">
        <CateTable :level="1" :key="`first-${refreshKey}`" />
      </el-tab-pane>
      <el-tab-pane label="二级分类" name="second">
        <CateTable :level="2" :key="`second-${refreshKey}`" />
      </el-tab-pane>
      <el-tab-pane label="三级分类" name="third">
        <CateTable :level="3" :key="`third-${refreshKey}`" />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加分类对话框 -->
    <el-dialog v-model="showDialog" title="添加分类" width="500px" @close="closeDialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="类别" prop="type">
          <el-select v-model="form.type" placeholder="请选择类别" class="full-width"
            @change="() => { form.fId = ''; form.sId = '' }">
            <el-option label="一级分类" :value="1" />
            <el-option label="二级分类" :value="2" />
            <el-option label="三级分类" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.type > 1" label="一级分类" prop="fId">
          <el-select v-model="form.fId" placeholder="请选择一级分类" class="full-width" @change="handleFirstLevelChange">
            <el-option v-for="item in cateStore.cateLevel" :key="item.id" :label="item.category" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.type === 3" label="二级分类" prop="sId">
          <el-select v-model="form.sId" placeholder="请选择二级分类" class="full-width">
            <el-option v-for="item in cateLevel2" :key="item.id" :label="item.category" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类名称" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类名称" class="full-width" maxlength="20" show-word-limit />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" :disabled="submitting">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ submitting ? '提交中...' : '确认' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.category-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-title {
      font-weight: bold;
      font-size: 16px;
    }
  }
}

.category-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 20px;
  }
}

.full-width {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>